<!-- 广告组词云 -->

<template>

  <div v-loading="loading" class="cloud-lalyout ">
    <el-tabs v-model="queryData.prop" @change="handleChagne">
      <el-tab-pane v-for="item in echartsOptions" :key="item.val" :label="item.name" :name="item.val" />
    </el-tabs>
    <div class="cloud-main">
      <div v-if="adchannelType!=='DISPLAY'" class="lt" :style="'min-height: '+minH+';'">
        <div class="title webfont-Bold">关键词</div>
        <div v-show="keyCloudShow" id="key-word" style="height: 380px;width: 100%;" />
        <div v-show="!keyCloudShow" style="text-align: center;position: absolute;top: 50%;left: 50%;transform: translate(-50% -50%);color: #909399;font-size: 14px;">暂无数据</div>
      </div>
      <div class="rt" :style="'min-height: '+minH+';'">
        <div class="title webfont-Bold">搜索词</div>
        <div v-show="searchCloudShow" id="search-word" style="height: 380px;width: 100%;" />
        <div v-show="!searchCloudShow" style="text-align: center;position: absolute;top: 50%;left: 50%;transform: translate(-50% -50%);font-size: 14px;color: #909399;">暂无数据</div>
      </div>
    </div>
    <!-- 关键词详情 -->
    <keyWordDetails v-if="oneKeyshow" :show.sync="oneKeyshow" :key-info="oneKeyInfo" :time-arr="timeArr" />
    <!-- 搜索词详情 -->
    <searchWordDetails v-if="oneSearchShow" :show1.sync="oneSearchShow" :time-arr="timeArr" :info="oneSearchInfo" />

  </div>

</template>

<script>
import 'echarts-wordcloud/dist/echarts-wordcloud'
import 'echarts-wordcloud/dist/echarts-wordcloud.min'
import searchWordDetails from './searchWordDetails.vue'
import keyWordDetails from './keyWordDetails.vue'
import {
  findReportKeywordList, // 查询广告系列组下的关键词表格
  findReportSearchTermList // 查询广告组下的搜索词表格
} from '@/api/keyWord.js'
import {
  mapGetters
} from 'vuex'

import {
  echartsOptions
} from '@/settings.js'
var timer = ''
// 词云中词云的样式设置
const itemSet = {
  textStyle: {
    // 回调函数 或 颜色值
    color: '#0085FF'
    // 鼠标hover的特效样式

  },
  emphasis: {
    textStyle: {
      color: '#39e61e'
    }
  }
}

export default {
  name: 'WordCloud',
  components: {
    searchWordDetails,
    keyWordDetails
  },
  props: {
    timeArr: {
      type: Object,
      default: () => {
        return ['2021-08-01', '2021-08-05']
      }
    },
    unitTxt: {
      type: String,
      default: function() {
        const unit = this.$store.state.user.unit
        if (unit === 'USD') {
          return '$'
        } else {
          return '￥'
        }
      }
    }

  },

  data() {
    return {
      loading: false,
      oneKeyshow: false, // 关键词详情的窗口显示
      oneKeyInfo: {}, // 单个关键词详情
      oneSearchShow: false,
      oneSearchInfo: {},
      queryData: {
        // 搜索数据的参数
        teamId: this.$store.state.team.teamId || '',
        currencyType: this.$route.query.currencyType || this.$store.state.user.unit,
        country: '',
        countrySX: this.$store.state.user.timeZone, // 时区
        timeZone: this.$store.getters.timeZoneTime, // 时区比UTC时间少几个小时
        prop: 'localSpendAmount', // 排序根据项
        pageNum: 1, // 第多少页；
        pageSize: 50, // 每页多少条
        matchType: '',
        name: '', // 查询时的名称  模糊查询
        status: '',
        order: 'descending', // 排序 /descending， ascending
        userId: this.$store.state.user.userInfo.userId,
        state: '',
        orgId: this.$route.query.orgId || '', // 如果是自助投放为空
        uuid: this.$route.query.uuid || '',
        aId: this.$route.query.aId || this.$route.query.aid || '',
        adgroupId: this.$route.query.adGroupId,
        campaignId: this.$route.query.campaignId,
        startTime: this.$store.state.overview.timeObj.overViewTime.startTime,
        endTime: this.$store.state.overview.timeObj.overViewTime.endTime

      },
      keyCloudShow: true,
      keyArr: [], // 假数据 关键词数据
      searchCloudShow: true,
      searchArr: [], // 假数据  搜索词数据
      keyCloud: undefined, // 关键词 词云盒子；
      searchCloud: undefined, // 搜索词 词云盒子；
      keyWordId: undefined, // 关键词 当前高亮词的Id;
      searchWordId: undefined, // 搜索词 当前高亮词的Id;
      option: { // 图表盒子的公共参数
        tooltip: {
          show: true,
          trigger: 'item',
          triggerOn: 'mousemove|click',
          backgroundColor: 'rgba(250, 250, 250, .95)',
          borderWidth: 0,
          shaowColor: 'rgba(0, 0, 0, .2)'
        },
        backgroundColor: '#fff',
        series: [{
          type: 'wordCloud',
          /*
                                                                                              绘制词云的形状, 值为回调函数 或 关键字, 默认 circle
                                                                                              关键字:
                                                                                              circle  圆形
                                                                                              cardioid 心形
                                                                                              diamond  菱形 正方形
                                                                                              triangle-forward, triangle  三角形
                                                                                              pentagon 五边形
                                                                                              star 星形
                                                                                               */
          shape: 'circle',
          // 用来调整词之间的距离
          // gridSize: 26,
          // 用来调整字的大小范围
          // Text size range which the value in data will be mapped to.
          // Default to have minimum 12px and maximum 60px size.
          sizeRange: [12, 32],
          // Text rotation range and step in degree. Text will be rotated randomly in range [-90,                                                                             90] by rotationStep 45
          // 用来调整词的旋转方向，，[0,0]--代表着没有角度，也就是词为水平方向，需要设置角度参考注释内容
          // rotationRange: [-45, 0, 45, 90],
          // rotationRange: [ 0,90],
          rotationRange: [0, 0],
          // 随机生成字体颜色
          // maskImage: maskImage,
          // 设置为true可以使单词部分在画布之外绘制, 允许绘制大于画布大小的单词
          drawOutOfBound: false,
          // 位置相关设置
          // Folllowing left/top/width/height/right/bottom are used for positioning the word cloud
          // Default to be put in the center and has 75% x 80% size.
          left: 'center',
          top: 'center',
          right: null,
          bottom: null,
          width: '100%',
          height: '380px'
          // 数据
          // data
        }]
      }
    }
  },
  computed: {
    ...mapGetters([
      'sidebar'
    ]),
    echartsOptions() {
      const arr = echartsOptions.map(item => {
        if (item.val === 'avgCptAmount' && this.adchannelType === 'DISPLAY') {
          return {
            name: 'CPM',
            val: 'avgCpmAmount',
            fix: '$'
          }
        } else {
          return item
        }
      })

      return arr
    },
    timeZone() {
      return this.$store.state.user.timeZone
    },

    opened() {
      return this.sidebar.opened
    },
    timeObj() {
      return this.$store.state.overview.timeObj.overViewTime
    },
    minH() {
      if (this.oneKeyshow || this.keyCloudShow) {
        return '436px'
      } else {
        return '236px'
      }
    }

  },
  watch: {
    // 时区变化
    timeZone: {
      deep: true,
      handler: function(newV, oldV) {
        this.getKeyWordArr()
        this.getSearchWordArr()
      }
    },

    // 时间变化
    timeObj: {
      deep: true,
      immediate: true,
      handler: function(newV, oldV) {
        this.queryData.startTime = newV.startTime
        this.queryData.endTime = newV.endTime
        this.getKeyWordArr()
        this.getSearchWordArr()
      }
    },

    // 侧边栏的收缩
    opened() {
      if (this.keyCloud) {
        const that = this
        this.$nextTick(() => {
          if (this.keyCloud && this.keyCloud.resize) {
            setTimeout(() => {
              that.keyCloud.resize()
            }, 200)
          }
        })
      }
      if (this.searchCloud) {
        const that = this
        this.$nextTick(() => {
          if (this.searchCloud && this.searchCloud.resize) {
            setTimeout(() => {
              that.searchCloud.resize()
            }, 100)
          }
        })
      }
    },

    // 关键词悬浮的时候  设置搜索词高亮
    keyWordId() {
      const highArr = []
      const lowArr = []
      this.searchArr.map((item, index) => {
        if (this.keyWordId && item.searchTermText === this.keyWordId) {
          highArr.push(index)
        } else {
          lowArr.push(index)
        }
      })

      // 显示高亮
      this.searchCloud.dispatchAction({
        type: 'highlight',
        seriesIndex: 0,
        dataIndex: highArr
      })

      // 取消高亮的元素
      this.searchCloud.dispatchAction({
        type: 'downplay',
        // 可选，系列 index，可以是一个数组指定多个系列
        seriesIndex: 0,
        dataIndex: lowArr

      })
    },

    'queryData.prop'(newValue, oldValue) {
      this.getKeyWordArr()

      this.getSearchWordArr()
    }

  },
  mounted() {
    this.keyCloud = this.$echarts.init(document.getElementById('key-word'))
    this.searchCloud = this.$echarts.init(document.getElementById('search-word'))

    // 监听浏览器窗口大小变化
    window.addEventListener('resize', () => {
      if (timer) {
        clearTimeout(timer)
      }
      timer = setTimeout(() => {
        if (this.keyCloud && this.keyCloud.resize) {
          this.keyCloud.resize()
        }
        if (this.searchCloud && this.searchCloud.resize) {
          this.searchCloud.resize()
        }
      }, 200)
    })

    // 监听关键词词云的双击事件
    this.keyCloud.on('dblclick', (params) => {
      // this.keyWordId = undefined
      this.oneKeyshow = true
      this.oneKeyInfo = JSON.parse(JSON.stringify(params.data))
    })

    // 监听搜索词词云的点击事件
    this.searchCloud.on('dblclick', (params) => {
      this.oneSearchShow = true
      this.oneSearchInfo = JSON.parse(JSON.stringify(params.data))
    })
  },

  // ���ٺ�
  destroyed() {
    // 移除监听
    window.removeEventListener('resize', () => {})
  },

  methods: {

    handleChagne() {
      this.getKeyWordArr()
      this.getSearchWordArr()
    },

    // 获取关键词前50
    async getKeyWordArr() {
      this.loading = true
      const res = await findReportKeywordList({ ...this.queryData,
        teamId: this.$store.state.team.teamId || ''
      })
      this.loading = false

      if (res.data.code === 20000) {
        const arr = res.data.data.list
        if (arr.length) {
          this.keyCloudShow = true
        } else {
          this.keyCloudShow = false
        }
        this.keyArr = JSON.parse(JSON.stringify(arr))
        this.initKeyCloud()
      } else {
        this.keyArr = []
      }
    },

    // 获取搜索词前50
    async getSearchWordArr() {
      this.loading = true
      this.queryData.adgroupId = this.$route.query.adGroupId * 1 || ''
      this.queryData.campaignId = this.$route.query.campaignId * 1 || ''
      const res = await findReportSearchTermList({ ...this.queryData,
        teamId: this.$store.state.team.teamId || ''
      })
      this.loading = false
      if (res.data.code === 20000) {
        const arr = res.data.data.list
        this.searchArr = []
        arr.forEach(item => {
          if (item.searchTermText !== '(低展示词)') {
            this.searchArr.push(item)
          }
        })

        if (this.searchArr.length) {
          this.searchCloudShow = true
        } else {
          this.searchCloudShow = false
        }

        this.initSearchCloud()
      } else {
        this.searchArr = []
      }
    },

    // 设置关键词词云的参数
    initKeyCloud() {
      const textIndex = echartsOptions.findIndex(item => {
        return item.val === this.queryData.prop
      })
      const textName = echartsOptions[textIndex].name

      const keyData = this.keyArr.map(item => {
        // 对数据进行循环，添加参数
        const that = this
        var obj = {
          ...item,
          ...itemSet,
          tooltip: {
            formatter: function(params, ticket, callback) {
              let str = `<p style="width:200px">${that.queryData.startTime} 至 ${that.queryData.endTime}</p>`
              str +=
                  `<p class="flex" style="color:#24BEBE;">
                          <span >${textName}：</span>
                          <span>
                          ${that.queryData.prop === 'localSpendAmount' || that.queryData.prop === 'avgCptAmount' || that.queryData.prop === 'avgCpaAmount' ? that.unitTxt : ''}
                          ${that.queryData.prop === 'taps' || that.queryData.prop === 'installs' || that.queryData.prop === 'impressions' ? params.data[that.queryData.prop] : (params.data[that.queryData.prop] * 1).toFixed(2)}
                          ${that.queryData.prop === 'ttr' || that.queryData.prop === 'conversionRate' ? '%' : ''}
                          </span>
                        </p>`

              for (let i = 0; i < echartsOptions.length; i++) {
                if (echartsOptions[i].val === that.queryData.prop) {
                  continue
                }
                str +=
                    `<p class="flex">
                            <span>${echartsOptions[i].name}：</span>
                            <span>
                            ${echartsOptions[i].val === 'localSpendAmount' || echartsOptions[i].val === 'avgCptAmount' || echartsOptions[i].val === 'avgCpaAmount' ? that.unitTxt : ''}
                            ${echartsOptions[i].val === 'taps' || echartsOptions[i].val === 'installs' || echartsOptions[i].val === 'impressions' ? params.data[echartsOptions[i].val] : (params.data[echartsOptions[i].val] * 1).toFixed(2)}
                            ${echartsOptions[i].val === 'ttr' || echartsOptions[i].val === 'conversionRate' ? '%' : ''}
                            </span>
                          </p>`
              }

              return str
            }
          },
          value: item[that.queryData.prop] * 1,
          name: item.text
        }
        return obj
      })

      // 设置图表的参数
      const keyOptions = JSON.parse(JSON.stringify(this.option))
      keyOptions.series[0].data = keyData
      this.keyCloud.setOption(keyOptions, true)

      this.keyCloud.on('mouseover', (params) => {
        this.keyWordId = params.data.keywordId
      })

      this.keyCloud.on('mouseout', (params) => {
        this.keyWordId = undefined
      })
    },

    // 设置搜索词词云的参数
    initSearchCloud() {
      const textIndex = echartsOptions.findIndex(item => {
        return item.val === this.queryData.prop
      })
      const textName = echartsOptions[textIndex].name
      const searchData = this.searchArr.map(item => {
        const that = this
        var obj = {
          ...item,
          ...itemSet,
          value: item[that.queryData.prop] * 1,
          name: item.searchTermText,
          tooltip: {
            formatter: function(params, ticket, callback) {
              let str = `<p style="width:200px">${that.queryData.startTime} 至 ${that.queryData.endTime}</p>`
              str +=
                  `<p class="flex" style="color:#24BEBE;">
			                <span >${textName}：</span>
			                <span>
			                ${that.queryData.prop === 'localSpendAmount' || that.queryData.prop === 'avgCptAmount' || that.queryData.prop === 'avgCpaAmount' ? that.unitTxt : ''}
			                ${params.data[that.queryData.prop]}
			                ${that.queryData.prop === 'ttr' || that.queryData.prop === 'conversionRate' ? '%' : ''}
			                </span>
			              </p>`

              for (let i = 0; i < echartsOptions.length; i++) {
                if (echartsOptions[i].val === that.queryData.prop) {
                  continue
                }
                str +=
                    `<p class="flex">
			                  <span>${echartsOptions[i].name}：</span>
			                  <span>
			                  ${echartsOptions[i].val === 'localSpendAmount' || echartsOptions[i].val === 'avgCptAmount' || echartsOptions[i].val === 'avgCpaAmount' ? that.unitTxt : ''}
			                  ${params.data[echartsOptions[i].val]}
			                  ${echartsOptions[i].val === 'ttr' || echartsOptions[i].val === 'conversionRate' ? '%' : ''}
			                  </span>
			                </p>`
              }

              return str
            }

            // formatter: function(params, ticket, callback) {
            //   let str = `<p style="width:200px">${that.queryData.startTime}至${that.queryData.endTime}</p>`
            //   for (let i = 0; i < echartsOptions.length; i++) {
            //     str +=
            //         `<p class="flex">
            //                 <span>${echartsOptions[i].name}：</span>
            //                 <span>${that.unitTxt}${params.data.[echartsOptions[i].val]}</span>
            //               </p>`
            //   }

            //   return str
            // }
          }
        }

        return obj
      })

      const searchOptions = JSON.parse(JSON.stringify(this.option))
      searchOptions.series[0].data = searchData
      this.searchCloud.setOption(searchOptions, true)
    }

  }

}
</script>
<style scoped lang="scss">
  .cloud-lalyout {

    .cloud-main {
      display: flex;
      justify-content: space-between;
      align-items: flex-start;
    }

    .lt {
      border-right: 1px solid rgba(57, 68, 78, 0.1);
      max-width: 50%;
    }

    .rt {
      padding-left: 68px;
      max-width: 50%;
    }

    .lt,
    .rt {
      flex: 1;
      position: relative;
      padding-bottom: 32px;

      .title {
        // font-weight: bold;
        font-size: 16px;
        line-height: 24px;
      }

    }
  }
</style>
